package mcts

import "bindolabs/gomoku/modules/gomoku_env"

type MCTSNode struct {
	Player         gomoku_env.PlayerType
	State          gomoku_env.State
	Parent         *MCTSNode
	Children       []*MCTSNode
	Visits         int
	Value          float64
	UntriedActions []*gomoku_env.Action
	Env            *gomoku_env.GomokuEnv

	//
	depth  int
	done   bool
	pos    string
	action *gomoku_env.Action // 父节点如何进入此节点的动作
}

func NewMCTSNode(env *gomoku_env.GomokuEnv, parent *MCTSNode) *MCTSNode {
	return &MCTSNode{
		Player:         env.Player,
		State:          env.GetState(),
		Parent:         parent,
		Children:       []*MCTSNode{},
		Visits:         0,
		Value:          0,
		UntriedActions: env.GetLegalActions(),
		Env:            env,

		done: false,
	}
}

func (node *MCTSNode) IsLeaf() bool {
	return len(node.Children) == 0
}

func (node *MCTSNode) AddChild(child *MCTSNode) {
	child.depth = int(node.Env.Count)

	node.Children = append(node.Children, child)
}

func (node *MCTSNode) Move(action *gomoku_env.Action) *MCTSNode {
	_, err := node.Env.Move(action)
	if err != nil {
		println("MCTSNode Move err:", err.Error())
		panic("")
	}

	newNode := NewMCTSNode(node.Env, node)
	newNode.action = action
	if node.Env.IsTerminal() {
		newNode.done = true
	}
	return newNode
}
